package org.wlw.user2;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UserManager {

    private Map<String,User> users;

    public UserManager() {
        users = new HashMap<>();
    }

    public User load(String username) {
        return users.get(username);
    }

    public void add(User user) {
        User tu = this.load(user.getUsername());
        if(tu!=null) {
            System.out.println("添加的用户已经存在!不能添加");
            return;
        }
        users.put(user.getUsername(),user);
        System.out.println("添加用户成功!");
    }

    public void update(User user) {
        User tu = this.load(user.getUsername());
        if(tu==null) {
            System.out.println("修改的用户不存在!");
            return;
        }
        tu.setAge(user.getAge());
        tu.setNickname(user.getNickname());
        tu.setPassword(user.getPassword());
        System.out.println("更新用户成功");
    }

    public void delete(String username) {
        if(this.load(username)==null) {
            System.out.println("删除的用户不存在!");
            return;
        }
        users.remove(username);
        System.out.println("删除用户成功!");
    }

    public void list() {
        Set<String> keys = users.keySet();
        for(String key:keys) {
            System.out.println(users.get(key));
        }
    }

    public User login(String username,String password) {
        User tu = this.load(username);
        if(tu==null) {
            System.out.println("用户名不正确!");
            return null;
        }
        if(!tu.getPassword().equals(password)) {
            System.out.println("密码不正确!");
            return null;
        }
        return tu;
    }
}
